package com.customization.unionpay.market.util;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.engine.cube.biz.ShardingActionHelper;
import weaver.conn.RecordSet;
import weaver.conn.RecordSetTrans;
import weaver.formmode.setup.ModeRightInfo;
import weaver.general.Util;
import weaver.hrm.User;
import weaver.integration.logging.Logger;
import weaver.integration.logging.LoggerFactory;

import java.util.ArrayList;
import java.util.List;

/**
 * @author sjm
 * @description 清算明细，汇总按钮相关
 */
public class ClearFundButtonRelated {

    private static final Logger log = LoggerFactory.getLogger(DailyReportRelated.class);

    /**
     * 判断资金类型和授权码类型是否一致
     *
     * @param code
     * @param zjly
     * @param workformId
     * @return
     */
    public static boolean compareToAuthCode(String code, String zjly, String workformId) {
        // 授权码尾号“1”位内部营销、尾号“2”为外部营销，尾号“3”为内外部联合营销
        boolean isTrue = false;
        String number = code.substring(code.length() - 1);
        log.info("number:"+number);
        String zjlyName = getTypeName(zjly, workformId);
        log.info("zjlyName:"+zjlyName);
        String zValue = "2";
        if ("内部营销".equals(zjlyName)) {
            zValue = "1";
        } else if ("内外部联合营销".equals(zjlyName)) {
            zValue = "3";
        }
        log.info("zValue:"+zValue);
        if (number.equals(zValue)) {
            isTrue = true;
        }

        return isTrue;
    }

    /**
     * 查询授权码尾号映射资金来源参数表单
     * @param zjly
     * @param sqmwh
     * @return
     */
    public static List<JSONObject> getTailNumberMappingFundSource(String zjly,String sqmwh){
        // 授权码尾号映射资金来源参数表单id
        int tailNumberMappingFundSourceFormId = Integer.parseInt(PropUtils.BB_LOG.getPropValue("marketSubject", "tail_number_mapping_fund_source_form_id"));
        log.info("tailNumberMappingFundSourceFormId：" + tailNumberMappingFundSourceFormId);
        String tableName = FormDataUtils.getTableName(tailNumberMappingFundSourceFormId);
        log.info("tableName：" + tableName);
        List<JSONObject> resultJsons = new ArrayList<>();
        RecordSet rst = new RecordSet();
        try {
            //获取流程基础信息
            StringBuilder sqls = new StringBuilder(" select sqmwh, zjly from ");
            sqls.append(tableName);
            sqls.append(" where 1 = 1 ");
            if(StrUtil.isNotBlank(zjly)){
                sqls.append("and zjly = '");
                sqls.append(zjly);
                sqls.append("' ");
            }
            if(StrUtil.isNotBlank(sqmwh)){
                sqls.append("and sqmwh = '");
                sqls.append(sqmwh);
                sqls.append("' ");
            }
            log.info("sqls:"+sqls.toString());
            rst.executeQuery(sqls.toString());

            if (rst.next()) {
                JSONObject itemInfo = new JSONObject();
                itemInfo.put("zjly", rst.getString("zjly"));
                itemInfo.put("sqmwh", rst.getString("sqmwh"));
                resultJsons.add(itemInfo);
            }
        } catch (Exception e) {
            log.error("根据授权码获取申请单和活动事项台账异常：" + e.getMessage());
        }
        return resultJsons;
    }

    /**
     * 获取营销事项申请单资金类型
     *
     * @param zjly
     * @param workformId
     * @return
     */
    public static String getTypeName(String zjly, String workformId) {
        String formId = FormDataUtils.getFormIdByWorkFlowId(workformId);
        if (!"".equals(formId)) {
            int formIdInt = Integer.parseInt(formId);
            return FormDataUtils.getItemName(formIdInt, "zjly", zjly);
        } else {
            log.error("通过流程表单id获取formid异常为空!");
            return "";
        }
    }

    /**
     * 根据授权码获取营销项目申请流程相关信息
     *
     * @param code
     * @return
     */
    public static JSONObject getMarketingApplicantInfoByCode(String workFormId, String tableName, String code) {
        // 申请单 内部资金合计 nbczjehj 资金来源 zjly 营销平台活动授权码 yxpthdsqm
        String workFlowTableName = FormDataUtils.getWorkFlowTableName(workFormId);
        // 活动事项台账  财务处理结束  cwsfjs 营销平台活动授权码 yxpthdsqm  已使用金额 ysyje
        RecordSet rst = new RecordSet();
        try {
            //获取流程基础信息
            String sqls = " select wt.nbczjehj as nbczjehj, " +
                    " wt.zjly as zjly, " +
                    " wt.nbsybl as nbsybl, " +
                    " wt.bdh as bdh, " +
                    " yx.cwsfjs as cwsfjs, " +
                    " yx.ysyje as ysyje " +
                    " from #{tableName1}  wt " +
                    " join #{tableName2}  yx " +
                    " on wt.yxpthdsqm = yx.yxpthdsqm " +
                    " where wt.yxpthdsqm = ? ";
            sqls = sqls.replace("#{tableName1}",workFlowTableName);
            sqls = sqls.replace("#{tableName2}",tableName);
            log.info("sqls:"+sqls);
            rst.executeQuery(sqls,code);
            if (rst.next()) {
                JSONObject itemInfo = new JSONObject();
                itemInfo.put("nbczjehj", rst.getString("nbczjehj"));
                itemInfo.put("cwsfjs", rst.getString("cwsfjs"));
                itemInfo.put("nbsybl", rst.getString("nbsybl"));
                itemInfo.put("zjly", rst.getString("zjly"));
                itemInfo.put("ysyje", rst.getString("ysyje"));
                itemInfo.put("bdh", rst.getString("bdh"));
                return itemInfo;
            }
        } catch (Exception e) {
            log.error("根据授权码获取申请单和活动事项台账异常：" + e.getMessage());
        }
        return null;
    }

    /**
     * 根据ids获取清算明细数据
     * @param tableName
     * @param ids
     * @return
     */
    public static List<JSONObject> getClearFundDetailsById(String tableName, String ids) {
        ids = ids.replace(",","','");
        log.info("ids:"+ids);
        RecordSet rst = new RecordSet();
        List<JSONObject> resultJsons = new ArrayList<>();
        try {
            //获取流程基础信息
            String sqls = " select id, yxpthdsqm, ACT_NM as act_nm, ACT_TOTAL_AT as act_total_at, ptqdrq, jbr, zbdw, qsje, ywlx, zjly, qsrq, sjly, hdjsbs, zt, zjzhlx from #{tableName} where id in ('"+ids+"')";
            sqls = sqls.replace("#{tableName}",tableName);
            log.info("sqls:"+sqls);
            rst.executeQuery(sqls);
            while (rst.next()) {
                JSONObject itemInfo = new JSONObject();
                itemInfo.put("id", Util.null2String(rst.getString("id")));
                itemInfo.put("yxpthdsqm", Util.null2String(rst.getString("yxpthdsqm")));
                itemInfo.put("act_nm", Util.null2String(rst.getString("act_nm")));
                itemInfo.put("act_total_at", Util.null2String(rst.getString("act_total_at")));
                itemInfo.put("ptqdrq", Util.null2String(rst.getString("ptqdrq")));
                itemInfo.put("jbr", Util.null2String(rst.getString("jbr")));
                itemInfo.put("zbdw", Util.null2String(rst.getString("zbdw")));
                itemInfo.put("qsje", Util.null2String(rst.getString("qsje")));
                itemInfo.put("ywlx", Util.null2String(rst.getString("ywlx")));
                itemInfo.put("zjly", Util.null2String(rst.getString("zjly")));
                itemInfo.put("qsrq", Util.null2String(rst.getString("qsrq")));
                itemInfo.put("sjly", Util.null2String(rst.getString("sjly")));
                itemInfo.put("hdjsbs", Util.null2String(rst.getString("hdjsbs")));
                itemInfo.put("zt", Util.null2String(rst.getString("zt")));
                itemInfo.put("zjzhlx", Util.null2String(rst.getString("zjzhlx")));
                resultJsons.add(itemInfo);
            }
        } catch (Exception e) {
            log.error("根据清算汇总获取清算明细数据异常：" + e.getMessage());
        }
        return resultJsons;
    }

    /**
     * 根据清算汇总获取清算明细数据
     *
     * @param ywlx 业务类型
     * @param zjly 资金来源
     * @param qsrq 清算日期
     * @param sjly 数据来源
     * @return
     */
    public static List<JSONObject> getClearFundDetailsByClearFundAllParams(String tableName, String ywlx, String zjly, String qsrq, String sjly) {

        RecordSet rst = new RecordSet();
        List<JSONObject> resultJsons = new ArrayList<>();
        try {
            //获取流程基础信息
            String sqls = " select id, yxpthdsqm, ACT_NM as act_nm, ACT_TOTAL_AT as act_total_at, ptqdrq, jbr, zbdw, qsje, hdjsbs, zt, zjzhlx from #{tableName} where ywlx like '%"+ywlx+"%' and zjly = '"+zjly+"' and qsrq = '"+qsrq+"' and sjly = '"+sjly+"' ";
            sqls = sqls.replace("#{tableName}",tableName);
            log.info("sqls：" + sqls);
            rst.executeQuery(sqls);
            while (rst.next()) {
                JSONObject itemInfo = new JSONObject();
                itemInfo.put("id", Util.null2String(rst.getString("id")));
                itemInfo.put("yxpthdsqm", Util.null2String(rst.getString("yxpthdsqm")));
                itemInfo.put("act_nm", Util.null2String(rst.getString("act_nm")));
                itemInfo.put("act_total_at", Util.null2String(rst.getString("act_total_at")));
                itemInfo.put("ptqdrq", Util.null2String(rst.getString("ptqdrq")));
                itemInfo.put("jbr", Util.null2String(rst.getString("jbr")));
                itemInfo.put("zbdw", Util.null2String(rst.getString("zbdw")));
                itemInfo.put("qsje", Util.null2String(rst.getString("qsje")));
                itemInfo.put("hdjsbs", Util.null2String(rst.getString("hdjsbs")));
                itemInfo.put("zt", Util.null2String(rst.getString("zt")));
                itemInfo.put("zjzhlx", Util.null2String(rst.getString("zjzhlx")));
                resultJsons.add(itemInfo);
            }
        } catch (Exception e) {
            log.error("根据清算汇总获取清算明细数据异常：" + e.getMessage());
        }
        return resultJsons;
    }

    /**
     * 根据ids查询清算汇总数据
     *
     * @param maintablename
     * @param ids
     * @return
     */
    public static List<JSONObject> getClearFundAllById(String maintablename, String ids) {
        ids = ids.replace(",","','");
        log.info("ids:"+ids);
        RecordSet rst = new RecordSet();
        // 根据当前信息使用id修改新建数据
        String sql = "select id,ywlx,zjly,qsrq,sjly,zt from #{tableName} where id in ('"+ids+"') ";
        sql = sql.replace("#{tableName}",maintablename);
        log.info("sql:"+sql);
        rst.executeQuery(sql);

        List<JSONObject> list = new ArrayList<>();
        while (rst.next()) {
            JSONObject json = new JSONObject();
            json.put("id", Util.null2String(rst.getString("id")));
            json.put("ywlx", Util.null2String(rst.getString("ywlx")));
            json.put("zjly", Util.null2String(rst.getString("zjly")));
            json.put("qsrq", Util.null2String(rst.getString("qsrq")));
            json.put("sjly", Util.null2String(rst.getString("sjly")));
            json.put("zt", Util.null2String(rst.getString("zt")));
            list.add(json);
        }
        return list;
    }

    /**
     * 根据唯一值查询清算汇总数据
     *
     * @param maintablename
     * @param ywlx
     * @param zjly
     * @param qsrq
     * @param sjly
     * @return
     */
    public static List<JSONObject> selectInfoBySth(String maintablename, String ywlx, String zjly, String qsrq, String sjly) {
        RecordSet rst = new RecordSet();
        // 根据唯一值查询清算汇总数据

        StringBuilder selectSql = new StringBuilder("select id,qsjehj from ");
        selectSql.append(maintablename);
        selectSql.append(" where ywlx ='");
        selectSql.append(ywlx);
        selectSql.append("' and zjly='");
        selectSql.append(zjly);
        selectSql.append("' and qsrq='");
        selectSql.append(qsrq);
        selectSql.append("' and sjly='");
        selectSql.append(sjly);
        selectSql.append("' ");
        log.info("sql:"+selectSql.toString());
        rst.executeQuery(selectSql.toString());

        List<JSONObject> list = new ArrayList<>();
        while (rst.next()) {
            JSONObject json = new JSONObject();
            json.put("id", Util.null2String(rst.getString("id")));
            json.put("qsje", Util.null2String(rst.getString("qsjehj")));
            list.add(json);
        }
        return list;
    }

    /**
     * 添加清算汇总数据
     *
     * @param formId
     * @param formmodeId
     * @param maintablename
     * @param user
     * @param ywlx
     * @param zjly
     * @param qsrq
     * @param sjly
     * @param qsje
     */
    public static void addInfoByFormId(int formId, int formmodeId, String maintablename, User user, String ywlx, String zjly, String qsrq, String sjly, String qsje) {
        RecordSetTrans rst = new RecordSetTrans();
        // 开启事务（关闭自动提交）
        rst.setAutoCommit(false);

        // 先调用内部方法新建一条数据，获取数据id
        int billid = FormDataUtils.getBillId(maintablename, formmodeId, user.getUID(), user.getType());

        try {
            // 获取formbizid
            String formBizId = ShardingActionHelper.constructBizId(billid, formId);

            // 根据当前信息使用id修改新建数据
            String updateSql = "update #{tableName} set ywlx=?, zjly=?, qsrq=?, sjly=?, qsjehj=?,zt='0', form_biz_id = ? where id = ? ";
            updateSql = updateSql.replace("#{tableName}",maintablename);
            log.info("updateSql:"+updateSql);
            rst.executeUpdate(updateSql,ywlx,zjly,qsrq,sjly,qsje,formBizId,billid);
            // 提交事务
            rst.commit();

            // 权限重构
            ModeRightInfo modeRightInfo = new ModeRightInfo();
            modeRightInfo.setNewRight(true);
            modeRightInfo.editModeDataShare(user.getUID(), formmodeId, billid);

        } catch (Exception e) {
            // 回滚
            rst.rollback();
            deleteByBillId(maintablename, billid);
            log.error("添加数据异常：" + e.getMessage());
        }
    }

    /**
     * 根据id修改清算汇总数据清算金额
     *
     * @param maintablename
     * @param id
     * @param qsje
     */
    public static void updateInfoById(String maintablename, String id, String qsje) {
        RecordSetTrans rst = new RecordSetTrans();
        // 开启事务（关闭自动提交）
        rst.setAutoCommit(false);
        try {
            // 根据当前信息使用id修改新建数据
            String updateSql = "update #{tableName} set  qsjehj=? where id = ? ";
            updateSql = updateSql.replace("#{tableName}",maintablename);
            log.info("updateSql:"+updateSql);
            rst.executeUpdate(updateSql,qsje,id);
            // 提交事务
            rst.commit();

        } catch (Exception e) {
            // 回滚
            rst.rollback();
            log.error("修改数据异常：" + e.getMessage());
        }
    }

    /**
     * 根据主表状态
     *
     * @param maintablename
     * @param billid
     */
    public static void updateStateByBillId(String maintablename, String zt, int billid) {
        RecordSetTrans rst = new RecordSetTrans();
        // 开启事务（关闭自动提交）
        rst.setAutoCommit(false);

        try {
            // 根据当前信息使用id修改新建数据
            String updateSql = "update #{tableName} set zt=? where id = ? ";
            updateSql = updateSql.replace("#{tableName}",maintablename);
            log.info("updateSql:"+updateSql);
            rst.executeUpdate(updateSql,zt,billid);
            // 提交事务
            rst.commit();
        } catch (Exception e) {
            // 回滚
            rst.rollback();
            log.error("修改状态异常：" + e.getMessage());
        }
    }

    /**
     * 根据id删除数据
     *
     * @param maintablename
     * @param billid
     */
    public static void deleteByBillId(String maintablename, int billid) {
        RecordSetTrans rst = new RecordSetTrans();
        // 开启事务（关闭自动提交）
        rst.setAutoCommit(false);

        try {
            // 根据当前信息使用id修改新建数据
            String updateSql = "delete from #{tableName} where id = ? ";
            updateSql = updateSql.replace("#{tableName}",maintablename);
            log.info("updateSql:"+updateSql);
            rst.executeUpdate(updateSql,billid);
            // 提交事务
            rst.commit();

        } catch (Exception e) {
            // 回滚
            rst.rollback();
            log.error("删除数据异常：" + e.getMessage());
        }
    }

    /**
     * 根据id删除数据
     *
     * @param maintablename
     * @param billid
     */
    public static void deleteDetailsByBillId(String maintablename, int billid) {
        RecordSetTrans rst = new RecordSetTrans();
        // 开启事务（关闭自动提交）
        rst.setAutoCommit(false);

        try {
            // 根据当前信息使用id修改新建数据
            String updateSql = "delete from #{tableName} where mainid = ? ";
            updateSql = updateSql.replace("#{tableName}",maintablename);
            log.info("updateSql:"+updateSql);
            rst.executeUpdate(updateSql,billid);
            // 提交事务
            rst.commit();

        } catch (Exception e) {
            // 回滚
            rst.rollback();
            log.error("删除数据异常：" + e.getMessage());
        }
    }
}
